/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Army.building;

import Army.BuildingAndUnit;
import Army.unit.Unit;
import GameObject.Sprite;
import GameObject.ValueBar;
import Global.ResourceManager;
import MOM.Message;
import MOM.Publisher;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.image.BufferedImage;
import java.util.ArrayList;

/**
 *
 * @author Huy
 */
public abstract class Building extends BuildingAndUnit implements Publisher {

	BufferedImage dustImg = ResourceManager.getImage("ingame/dust");
	ArrayList<Unit> listUnits = new ArrayList<>();
	int maxContain = 9;

	public boolean addUnit(Unit unit) {
		if (listUnits.size() < maxContain) {
			unit.setPosition(approximate(getPosition(), 2));
			listUnits.add(unit);
			return true;
		}
		return false;
	}

	public void train() {
		if (listUnits.isEmpty()) {
			return;
		}
		Unit u = listUnits.get(0);
		if (u.isCompleted()) {
			post(team, new Message(u, "add"));
			listUnits.remove(0);
		}
		u.build();
	}

	public Point approximate(Point p, int d) {
		int dx = (int) (Math.random() * d + 1);
		if (Math.random() > 0.5) {
			dx = -dx;
		}
		int dy = (int) (Math.random() * d + 1);
		if (Math.random() > 0.5) {
			dy = -dy;
		}
		return new Point(p.x + dx, p.y + dy);
	}

	public ArrayList<Unit> getListUnits() {
		return listUnits;
	}

	public Building() {
	}

	@Override
	public Sprite getHitedEffect(int x, int y) {
		Sprite spt = new Sprite(dustImg, 5, 1, x, y);
		spt.setSequence(0);
		spt.setInnerPoint(new Point(10, 10));
		return spt;
	}
	static Color barBuildColor = new Color(0, 0, 1, 0.8f);
	static Color barBackColor = new Color(1, 1, 1, 0.3f);

	@Override
	public void draw(Graphics2D g, int dx, int dy) {
		sprite.draw(g, dx, dy);
		if (!completed) {
			double value = (double) healthPoint / maxHealthPoint;
			int barWidth = 5;
			ValueBar bar = new ValueBar(barBackColor, Color.blue, value, getPosition().x - size / 2, getPosition().y - barWidth / 2, size, barWidth);
			bar.draw(g, dx, dy);
		}
		if (isSelected) {
			g.setColor(Color.WHITE);
			g.drawRect(getPosition().x - size / 2 + dx, getPosition().y - size / 2 + dy, size, size);
		}
	}

	@Override
	public boolean isBuilding() {
		return true;
	}

	@Override
	public void incHealthPoint(int dHp) {
		healthPoint += dHp;
		if (healthPoint < 0) {
			healthPoint = 0;
		} else if (healthPoint > maxHealthPoint) {
			healthPoint = maxHealthPoint;
		}
		if (Math.random() > 0.5 && dHp < 0) {
			post(team, new Message(this, "attacked"));
		}
	}
	
}
